﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using Snowflake.Entity;

namespace Snowflake.Gateway
{
    internal class DeleteQuery<TEntity> : EntityQuery<TEntity> where TEntity : EntityObject<TEntity>, new()
    {
        public DeleteQuery(IQueryable<TEntity> query)
            : base(query) { }

        protected internal override string TranslateSQLQuery(string tableName, string commandText, DbParameterCollection parameters)
        {
            StringBuilder builderCommand = new StringBuilder();
            builderCommand.AppendLine("DECLARE delete_cursor CURSOR FOR ");
            builderCommand.AppendLine(commandText + " ");
            builderCommand.AppendLine("OPEN delete_cursor ");
            builderCommand.AppendLine("FETCH FROM delete_cursor ");
            builderCommand.AppendLine("WHILE @@FETCH_STATUS = 0 ");
            builderCommand.AppendLine(" BEGIN ");
            builderCommand.AppendFormat("  DELETE FROM {0} WHERE CURRENT OF delete_cursor", tableName);
            builderCommand.AppendLine(Environment.NewLine + "  FETCH NEXT FROM delete_cursor ");
            builderCommand.AppendLine(" END ");
            builderCommand.AppendLine("CLOSE delete_cursor ");
            builderCommand.AppendLine("DEALLOCATE delete_cursor ");

            return builderCommand.ToString();
        }
    }
}
